﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Rotempco.BaseClass;
using Rotempco.BaseClass.Logic;
using Rotempco.BaseClass.Objects.EntityObjects;
using Rotempco.BaseClass.Objects.Enums;
using Rotempco.BaseClass.Objects.ReturnObjects;
using Rotempco.Website.Objects;
using Rotempco.Core.Web.Logic;
using Rotempco.Core.Logic;

namespace Rotempco.Website.WebPages.Admin.ChangePassword
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoginUser loginUser = SessionStore.Instance.LoginUser;
                WebFormFiller.FillForm<LoginUser>(loginUser, this);
            }
        }

        protected bool userControl_EditBottomPanel_OnSaveEvent()
        {
            LoginUser loginUser = SessionStore.Instance.LoginUser;

            if (loginUser == null)
                throw new Exception("You must be logged in to access this page");

            if (textBox_NewPassword.Text.Length == 0 || textBox_RetypeNewPassword.Text.Length == 0)
            {
                userControl_EditBottomPanel.SetErrorMessage("You must fillout all fields!");
                return false;                
            }

            if (textBox_NewPassword.Text != textBox_RetypeNewPassword.Text)
            {
                userControl_EditBottomPanel.SetErrorMessage("The 2 passwords are not identical!");
                return false;
            }
            
            loginUser.PasswordHash = HashLogic.GetHash(textBox_NewPassword.Text);
            ChangePasswordResultEnum changePasswordResultEnum = Factory.LoginUser.ChangePassword(loginUser, textBox_NewPassword.Text );

            switch (changePasswordResultEnum)
            {
                case ChangePasswordResultEnum.InvalidPassword:
                    label_Status.Text = "New password is not valid!";
                    break;
                case ChangePasswordResultEnum.Success:
                    label_Status.Text = "Your password has been changed succesfully!";
                    SessionStore.Instance.LoginUser = loginUser;
                    break;
                case ChangePasswordResultEnum.EncryptionKeyError:
                default:
                    label_Status.Text = "An error has occurred!";
                    break;
            }
            return false;

        }
    }
}